//
//  LargePicController.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/20.
//  Copyright (c) 2015年 bing. All rights reserved.
//  大图浏览

import UIKit
import SDWebImage
import SVProgressHUD

class LargePicController: UIViewController, UIScrollViewDelegate {

    
    // 提供缩放比例
    var scale:CGFloat = 1
    
    var largeImage:UIImage? {
        didSet {
            myiconview.image = largeImage
            myiconview.frame = calcLargeFrame(largeImage!.size)
        }
    }
    
    
    // 根据图片大小计算imageview的大小,且屏幕居中
    private func calcLargeFrame(imageSize: CGSize) -> CGRect {
    
        // 判断长短图,通过成比例的高度宽度判断
        let imgviewW = UIScreen.mainScreen().bounds.width
        let imgviewH = imageSize.height * imgviewW / imageSize.width
        
        // 比屏幕长,是长图,否则是短图
        if imgviewH > UIScreen.mainScreen().bounds.height {
            
            // 长图的处理,将图片右上角置于屏幕右上角
            myscrollview.contentSize = CGSizeMake(imgviewW, imgviewH)
        } else {
            
            // 图片需要居中
            let top = (view.bounds.height - imgviewH) * 0.5
            myscrollview.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        }
        return CGRectMake(0, 0, imgviewW, imgviewH)
        
    }
    
    
    var largeUrl:NSURL? {
        didSet {
            // 清空cell中得内容
            clearCellcontent()
            
            SVProgressHUD.show()
            SDWebImageManager.sharedManager().downloadImageWithURL(largeUrl, options: nil, progress: nil) { (image, _, _, _, _) -> Void in
                if image != nil {
                    self.largeImage = image
                }
                SVProgressHUD.dismiss()
                SVProgressHUD.showErrorWithStatus("图片下载失败")
            }
        }
    }
    
    private func clearCellcontent() {
        myiconview.image = nil
        myscrollview.contentSize = CGSizeZero
        myscrollview.contentOffset = CGPointZero
        myscrollview.contentInset = UIEdgeInsetsZero
    }
    

    lazy var myscrollview: UIScrollView = {
        let myscrollview = UIScrollView(frame: self.view.bounds)
        
        // 设置缩放比例
        myscrollview.minimumZoomScale = 0.5
        myscrollview.maximumZoomScale = 2.0
        myscrollview.delegate = self
        
        return myscrollview
    }()
    
    
    lazy var myiconview: UIImageView = {
        let myiconview = UIImageView()
        return myiconview
    }()
    
    
    override func loadView() {
        super.loadView()
        view = UIView(frame: UIScreen.mainScreen().bounds)
        myscrollview.addSubview(myiconview)
        view.addSubview(myscrollview)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - UIScrollView代理
    // 返回要缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return myiconview
    }
    
    
    // 缩放完成后,手势结束后调用 
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
        
        // 判断整体缩放比例 < 1.0 说明交互式转场
        if scale < 1.0 {
            completeTransition(true)
            return
        }
        
        // 再次调整图像间距,重新计算顶部的间距值
        let top = (scrollView.frame.height - view.frame.height) * 0.5
        if top > 0 {
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        } else {
            scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    
    // 正在缩放视图
    func scrollViewDidZoom(scrollView: UIScrollView) {
        if myiconview.transform.a < 1.0 {
            scale = myiconview.transform.a
            
            // 开始交互
            startInteractiveTransition(self)
        }
    }
    

}



// 转场动画
// MARK: - UIViewControllerAnimatedTransitioning 代理 (相互作用转场)
extension LargePicController : UIViewControllerInteractiveTransitioning {
    
    // 开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        // 将目标控制器添加到当前视图中
//        let toViewVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
//        let toview = toViewVC!.view
        
        // 快照,利用快照作为背景,可以建立目标视图的快照
//        let dummyView = toview.snapshotViewAfterScreenUpdates(false)
//        transitionContext.containerView().insertSubview(dummyView, belowSubview: view)
        
        // 将当前的视图控制器的视图 alpha 降低
        view.transform = CGAffineTransformMakeScale(scale, scale)
        view.alpha = scale
    }
    
}



// MARK: - LargePicController (转场上下文)
extension LargePicController : UIViewControllerContextTransitioning {
    
    // 转场容器视图
    func containerView() -> UIView {
        return view.superview!
    }
    
    // 是否转场结束
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 参与转场的视图控制器 - 提供转场到哪里的控制器
    func viewControllerForKey(key: String) -> UIViewController? {
        
        if key == UITransitionContextToViewControllerKey {
            return UIApplication.sharedApplication().keyWindow!.rootViewController
        } else {
            return self
        }
    }
    
    
    // 可以不用函数
    func isAnimated() -> Bool {
        return true
    }
    
    func isInteractive() -> Bool {
        return true
    }
    
    func transitionWasCancelled() -> Bool {
        return false
    }
    
    func presentationStyle() -> UIModalPresentationStyle {
        return UIModalPresentationStyle.Custom
    }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    
    func finishInteractiveTransition() {}
    
    func cancelInteractiveTransition() {}
    
    func viewForKey(key: String) -> UIView? {
        return nil
    }
    
    func targetTransform() -> CGAffineTransform {
        return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
    
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
}


